<?php

namespace App\Http\Controllers\lxSystem;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Category;

class CategoryController extends Controller
{
    function __construct()
    {
        view()->share([
            'categories'=>Category::get_categories()
        ]);
    }

    function index(){
        return view('lxSystem.categories.index');
    }

    function create(){
        return view('lxSystem.categories.create');
    }

    function store(Request $request){
        Category::create($request->all());
        return redirect(route('categories.index'));
    }

    function edit($id){
        $category=Category::find($id);
        return view('lxSystem.categories.edit')->with('category',$category);
    }

    function update(Request $request,$id){
        $category=Category::find($id);
        $category->update($request->all());
        return redirect(route('categories.index'));
    }
    
    function destroy($id){
        if(!Category::check_children($id)){
            return back()->with('error', '当前分类有子分类，请先将子分类删除后再尝试删除~');
        }
        Category::destroy($id);
        return redirect(route('categories.index'))->with('success', '删除成功');
    }

    function sort_order(Request $request){
        $category=Category::find($request->id);
        $category->sort_order=$request->sort_order;
        $category->save();
    }

    function is_something(Request $request){
        $attr = $request->attr;
        $category = Category::find($request->id);
        $value = $category->$attr ? false : true;
        $category->$attr = $value;
        $category->save();
    }
}
